/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ts, rule } from "qvog-dsl";

const SEVERITY = 2;
const DOC_PATH = 'docs/consistent-type-imports-check.md';
const DESCRIPTION = 'Enforce consistent usage of type imports.';

enum TypeImportsPrefer {
    noType = 0,
    type = 1
}

let prefer = 1;

function containsAssert(nodeList: ts.Node[]): boolean {
    for (const node of nodeList) {
        if (ts.isAssertClause(node)) {
            return true;
        }
    }
    return false;
}

export default rule()
    .match((node): node is ts.ImportDeclaration => ts.isImportDeclaration(node))
    .when((node): boolean => {
        const nodeList = node.getChildren();
        if (nodeList.length < 3 || containsAssert(nodeList)) {
            return false;
        };
        const second = nodeList[1];
        if (!ts.isImportClause(second)) {
            return false;
        };
        const secondNodeList = second.getChildren();
        if (secondNodeList.length < 1) {
            return false;
        };
        const secondFirst = secondNodeList[0];
        const hasType = secondFirst.kind === ts.SyntaxKind.TypeKeyword;
        if ((prefer === TypeImportsPrefer.noType && hasType) ||
            (prefer === TypeImportsPrefer.type && !hasType)) {
            return true;
        };
        return false;
    })
    .report({
        severity: SEVERITY,
        description: DESCRIPTION,
        docPath: DOC_PATH,
    });
